'use strict';
const inquirer = require('inquirer')
const fxExtra = require('fs-extra')
const path = require('path')
const semver = require('semver')
const useHome = require('user-home')
const Command = require('@baseh-cli-dev/command')
const Package = require('@baseh-cli-dev/package')
const log = require('@baseh-cli-dev/log')
const getProjectTemplate = require('./getProjectTemplate')
const fs = require('fs')

const TYPE_PROJECT = 'project'
const TYPE_COMPONENT = 'component'
const TEMPLATE_TYPE_NORMAL = 'normal'
const TEMPLATE_TYPE_CUSTOM = 'custom'

class InitCommand extends Command {
  init () {
    this.projectName = this._argv[0] || ''
    this.force = !!this._cmd.force
  }

  async exec () {
    try {
      console.log('exec')
      // 准备
      const projectInfo = await this.prepare()
      if (projectInfo) {
        // 下载
        log.verbose('projectInfo', projectInfo)
        this.projectInfo = projectInfo
        await this.downTemplate()
        // 安装
        await this.installTemplate()
      }

    } catch(e) {
      log.error(e.message)
    }
  }

  async installTemplate () {
    console.log(this.templateInfo)
    if (this.templateInfo) {
      if (!this.templateInfo.type) {
        this.templateInfo.type = TEMPLATE_TYPE_NORMAL
      }

      if (this.templateInfo.type === TEMPLATE_TYPE_NORMAL) {
        // 标准安装
        await this.installNormalTemplate()
      } else if (this.templateInfo.type === TEMPLATE_TYPE_CUSTOM) {
        // 自定义安装
        await this.installCustomTemplate()
      } else {
        throw new Error('项目模版类型无法识别')
      }
    } else {
      throw new Error('项目模版不存在')
    }
  }

  async installNormalTemplate () {
    console.log(this.templateNpm)
    // 拷贝模版代码至当前目录
    try {
      const templatePath = path.resolve(this.templateNpm.cacheFilePath, 'template')
      const targetPath = process.cwd()
      fxExtra.ensureDirSync(templatePath)
      fxExtra.ensureDirSync(targetPath)
      fxExtra.copySync(templatePath, targetPath)
    } catch(e) {
      throw e
    } finally {
      // 安装完成
      log.success('安装完成')
    }
  }

  async installCustomTemplate () {

  }

  async downTemplate () {
    // 1. 通过项目模版api获取项目模版信息
    // 通过egg。js 搭建一套后端模版
    // 通过npm存储项目模版
    // 将项目模版信息存到mongdb数据库中
    // 通过egg 获取mongdb中的数据并通过荥返回
    const {projectTemplate} = this.projectInfo
    // const templateInfo = this.template.find(item => item.npmName == projectTemplate)

    const templateInfo = {npmName: '@baseh-cli-dev/template', version: '1.0.0'}
    const targetPath = path.resolve(useHome, '.baseh-cli-dev', 'template')
    const storeDir = path.resolve(useHome, '.baseh-cli-dev', 'template', 'node_modules')
    const {npmName, version} = templateInfo
    // console.log(npmName, version, templateInfo)
    this.templateInfo = templateInfo
    const templateNpm = new Package({
      targetPath,
      storeDir,
      packageName: npmName,
      packageVersion: version
    })

    //console.log(targetPath, storeDir, npmName, version, templateNpm)
    if (!await templateNpm.exists()) {
      console.log(await templateNpm.exists())
      try {
        await templateNpm.install()
        console.log('templateNpm.install')
      } catch(e) {
        throw e
      } finally {
        console.log(await templateNpm.exists())
        if (await templateNpm.exists()) {
          console.log('templateNpm.install111')
          log.success('下载模版成功')
          this.templateNpm = templateNpm
        }
      }
      // return
    } else {
      try {
        await templateNpm.update()
      } catch(e) {
        throw e
      } finally {
        if (await templateNpm.exists()) {
          log.success('更新模版成功')
          this.templateNpm = templateNpm
        }
      }

    }
  }

  async prepare () {
    // const template = await getProjectTemplate()
    // if (!template || template.length === 0) {
    //   throw new Error('模版信息不存在')
    // }
    // this.template = template
    const localPath = process.cwd()
    let ifContinue = false
    // 当前目录是否为空
    if (!this.isCwdEmpty(localPath)) {
      if (!this.force) {
        ifContinue = (await inquirer.prompt({
          type: 'confirm',
          name: 'ifContinue',
          message: '当前文件夹不为空，是否继续创建项目'
        })).ifContinue

        if (!ifContinue) {
          return
        }
      }

      // 是否启动强制更新
      if (ifContinue || this.force) {
        const {confirmDelete} = await inquirer.prompt({
          type: 'confirm',
          name: 'confirmDelete',
          message: '是否确认清空当前目录文件？'
        })
        if (confirmDelete) {
          fxExtra.emptyDirSync(localPath)
        }
      }
    }
    return this.getProjectInfo()
  }

  async getProjectInfo () {
    let projectInfo = {}
    // 选择创建项目或组件
    const {type} = await inquirer.prompt({
      type: 'list',
      name: 'type',
      message: '请选择初始化类型',
      default: TYPE_PROJECT,
      choices: [{
        name: '项目',
        value: TYPE_PROJECT
      }, {
        name: '组件',
        value: TYPE_COMPONENT
      }]
    })

    // 获取项目的基本信息
    if (type === TYPE_PROJECT) {
      const project = await inquirer.prompt([{
        type: 'input',
        message: '请输入项目名称',
        name: 'projectName',
        default: '',
        validate: function (v) {
          const done = this.async()
          setTimeout(function () {
            if (!/^[a-zA-Z]+([-][a-zA-Z][a-zA-Z0-9]*|[_][a-zA-Z][a-zA-Z0-9]*|[a-zA-Z0-9])*$/.test(v)) {
              done('请输入合法的项目名称')
              return
            }

            done(null, true)
          }, 0)

          // 1 首尾为英文字符
          // return /^[a-zA-Z]+[\w-]*[a-zA-Z0-9]$/.test(v)
          //return /^[a-zA-Z]+([-][a-zA-Z][a-zA-Z0-9]*|[_][a-zA-Z][a-zA-Z0-9]*|[a-zA-Z0-9])*$/.test(v)
          // return typeof v == 'string'
        },
        filter: function (v) {
          return v
        }
      }, {
        type: 'input',
        name: 'projectVersion',
        message: '请输入项目版本号',
        default: '1.0.0',
        validate: function (v) {
          const done = this.async()
          setTimeout(function () {
            if (!(!!semver.valid(v))) {
              done('请输入合法的项目版本号')
              return
            }

            done(null, true)
          }, 0)

          // return !!semver.valid(v)
          // return typeof v == 'string'
        },
        filter: function (v) {
          if (semver.valid(v)) {
            return semver.valid(v)
          } else {
            return v
          }

        }
      }, {
        type: 'list',
        name: 'projectTemplate',
        message: '请选择项目模版',
        choices: this.createTemplateChoice()
      }])

      // console.log(o)
      projectInfo = {
        type,
        ...project
      }
    } else if (type === TYPE_COMPONENT) {

    }

    return projectInfo
  }

  isCwdEmpty (localPath) {
    let fileList = fs.readdirSync(localPath)
    fileList = fileList.filter(file => {
      return !file.startsWith('.') && ['node_modules'].indexOf(file) < 0
    })

    return !fileList || fileList.length <= 0
  }

  createTemplateChoice () {
    // return this.template.map(item => ({
    //   value: item.npmName,
    //   name: item.name
    // }))

    return [{value: '@baseh-cli-dev/template', name: 'vue3标准模版'}]
  }
}

function init (argv) {
  // console.log('init', projectName, cmdObj.force, process.env.CLI_TARGET_PATH)
  return new InitCommand(argv)
}

module.exports = init
module.exports.InitCommand = InitCommand;